<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="部门名字或者编号"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getDepartments">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<!--{id sn name dirPath state manager_id parent_id manager parent} -->
		<el-table :data="departments"   @row-dblclick="yyyyy" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55"></el-table-column>
			<el-table-column type="index" width="60"></el-table-column>
			<el-table-column prop="name" label="部门名称" width="120" sortable></el-table-column>
			<el-table-column prop="sn" label="部门编号" width="120" sortable></el-table-column>
			<el-table-column prop="dirPath" label="父级部门" width="120" sortable></el-table-column>
			<!--插槽vue-->
			<el-table-column prop="state" label="性别" width="100" sortable>
				<template scope="scope"> <!--使用当前作用范围的数据： row 行数据放入scope作用域-->
					<span v-if="scope.row.state===1" style="color: green">启用</span>
					<span v-else-if="scope.row.state===0" style="color: red">禁用</span>
					<span v-else style="color: blue">未知</span>
				</template>
			</el-table-column>

			<el-table-column prop="manager.username" label="部门经理" width="120" sortable></el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="120" sortable></el-table-column>

			<el-table-column label="操作" align="center">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" :current-page="currentPage" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog v-bind:title="title" v-bind:visible.sync="editFormVisible" :close-on-click-modal="true">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门名字" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="editForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="部门经理">


					<!--
					     1.v-for="emp in employees" 遍历双向绑定的：  employees 值  emp 遍历出来的每一个employee对象
					     2.:label="emp.username"  当你选中之后，显示内容
					     3.value="emp">  value 提交到 后段的值emp对象{}  选中之后的一个值
                         4.如果你的value选的是对象    一定要   select  value-key="id"
					-->
					<!--<el-input v-model="editForm.manager" auto-complete="off"></el-input>-->
					<el-select v-model="editForm.manager"  value-key="id" placeholder="请选择">
						<el-option
								v-for="emp in employees"
								:label="emp.username"
								:value="emp">
							<span style="float: left">{{ emp.username }}</span>
							<span style="float: right; font-size: 13px">{{ emp.phone }}</span>
						</el-option>
					</el-select>



				</el-form-item>
				<el-form-item label="上级部门">
					<!--<el-input v-model="editForm.parent" auto-complete="off"></el-input>-->
					<!--
							1.editForm.parent：  是双向绑定  给值this.editForm.parent= [2,5]
							2.options  绑定的级联数据
							3. label:'name',value:'id'
							    在向deptTree[{id:1,name:"dept1"},{id:2,name:"dept2"},{id:3,name:"dept3"}]

					-->
					<el-cascader v-model="editForm.parent"
							:options="deptTree"
							:props="{checkStrictly: true,label:'name',value:'id' }"
							clearable>
					</el-cascader>



				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>


		<el-drawer
				title="我是标题"
				:visible.sync="drawer"
				:direction="direction"
				:before-close="handleClose">
			<span>

			</span>
		</el-drawer>



	</section>
</template>

<script>

	export default {
		data() {
			return {
				filters: {
					keyword: ''
				},
				title:"",
				departments: [],
				employees:[],
				deptTree:[],
				total: 0,
				pageSize: 5,
				currentPage:1,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
					sn: [
						{ required: true, message: '请输入编号', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
					name: "",
					sn: "",
					state: 0,
					manager: "",
					parent: ""
				},


				addLoading: false,
				drawer: false,
				direction: 'rtl'
			}
		},
		methods: {
			handleClose(done) {
				this.$confirm('确认关闭？')
						.then(_ => {
							done();
						})
						.catch(_ => {});
			},
		    yyyyy(row,clum,evernt){
			     this.drawer=true
		    },
			bbbbbb(){
				alert(2)
			},
			//性别显示转换
			/*formatState: function (row, column) {//row 这一行的数据
				return row.state == 1 ? '<span style="green">启用</span>' : row.state == 0 ? '禁用' : '未知';
			},*/
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},
			//获取部门列表
			getDepartments() {
				let para = {
					currentPage: this.currentPage,
					pageSize: this.pageSize,
					keyword:this.filters.keyword
				};
				//this.listLoading = true;  //忙态框
				//pageList   {totalCount:"",data:[{},{}]}   json----对象
				//User id ,name {id:"",name:""}
				//Map   {}
				//List<User>    [{},{},{}]
				//result.data
				this.$http.post("/department",para)
					.then(result=>{
						console.log("请求的分页数据---------------------------------：",result)
						result = result.data
						this.departments = result.data
						this.total = result.totalCount
					}).catch(result=>{
						console.log(result)
				})
				//NProgress.start();
				/*getDepartmentListPage(para).then((res) => {
					this.total = res.data.total;
					this.departments = res.data.departments;
					this.listLoading = false;
					//NProgress.done();
				});*/
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.delete("/department/"+row.id)
						.then(result=>{  //  result{data:AjaxResult{success:true,msg:"xxxx"}}
							this.listLoading = false;
							//let {success,msg} = result.data;//{success:true,msg:"xxxx"}
							if(result.data.success){//成功
								this.getDepartments()
								this.$message({
									message: result.data.msg,
									type: 'success'
								});
							}else{//失败
								this.$message({
									message: result.data.msg,
									type: 'error'
								});
							}
						}).catch(result=>{

					})


					/*removeDepartment(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDepartments();
					});*/
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {

				this.title = "编辑"
				this.editFormVisible = true;
				this.editForm = Object.assign(row,{});//  把一行的数据拷贝，给到绑定的    editForm
				let arr = row.dirPath.split("/") /*    /2/5/8     [,2,5,8] */
				arr = arr.slice(1,arr.length-1)
				for(var i in arr){//i 索引
					arr[i] = parseInt(arr[i])
				}
				this.editForm.parent = arr
			},
			//显示新增界面
			handleAdd: function () {
				this.title="新增"
				this.editFormVisible = true;
				this.editForm = {
					state:1
				};
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {//使用校验规则，校验表单是否符合校验规则
					if (valid) {// 如果为true
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();

							//【拷贝】了双向绑定的editForm  拿到模态框，填写的数据
							//提交的数据{id:11,name:"dept1",manager:{},parent:[2,5]}
							//提交的数据{id:11,name:"dept1",manager:{},parent:{id:5}}
							let para = Object.assign({}, this.editForm);
							let arr = para.parent
							if(arr){//  如果我不选择上级部门们： arr undifined
								para.parent = {id:arr[arr.length-1]}
							}

							console.log("let para = Object.assign({}, this.editForm);",para)
							this.$http.put("/department",para)
								.then(result=>{
									this.editLoading = false;
									this.editFormVisible = false;
									if(result.data.success){
										this.getDepartments();//操作成功，之后重新加载数据
										this.$message({
											message: result.data.msg,
											type: 'success'
										});
									}else{
										this.$message({
											message: result.data.msg,
											type: 'error'
										});
									}
								})


							/*para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							editDepartment(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getDepartments();
							});*/
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);//ids  [1, 2, 5, 7, 8]
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					console.log("para:",ids)
					this.$http.patch("/department",ids)
						.then(result=>{//ajaxResult
							this.listLoading = false;
							if(result.data.success){//删除成功
								this.getDepartments()
								this.$message({
									message: result.data.msg,
									type: 'success'
								});
							}else{
								this.$message({
									message: result.data.msg,
									type: 'error'
								});
							}
						})

					/*batchRemoveDepartment(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDepartments();
					});*/
				}).catch(() => {

				});
			},
			/*查询所有的员工*/
			getEmps(){
				this.$http.get("/employee")
					.then(result=>{
						this.employees = result.data
					})
			},
			getDeptTree(){
				this.$http.get("/department/tree")
					.then(result=>{
						console.log("部门树：",result.data)
						this.deptTree = result.data
					})
			}
		},
		mounted() {  //页面加载的时候，执行
			this.getDepartments();
			this.getEmps()
			this.getDeptTree()

		}
	}

</script>

<style scoped>

</style>